import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';

import 'global_search_logic.dart';

class GlobalSearchPage extends StatelessWidget {
  final logic = Get.find<GlobalSearchLogic>();

  GlobalSearchPage({super.key});

  @override
  Widget build(BuildContext context) {
    return TouchCloseSoftKeyboard(
      child: Scaffold(
        backgroundColor: Styles.c_F8F9FA,
        appBar: _buildAppBar(),
        body: Column(
          children: [
             Obx(() => logic.searchFriendOnly.value
                ? const SizedBox.shrink()
                : _buildSearchTypeFilter()),
            Expanded(
              child: Obx(() => _buildSearchContent()),
            ),
          ],
        ),
      ),
    );
  }

    // 构建应用栏
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Styles.c_FFFFFF,
      elevation: 0,
      leading: IconButton(
        icon: Icon(Icons.arrow_back, color: Styles.c_0C1C33),
        onPressed: () => Get.back(),
      ),
      title: Container(
        height: 36.h,
        decoration: BoxDecoration(
          color: Styles.c_F8F9FA,
          borderRadius: BorderRadius.circular(18.r),
        ),
        child: TextField(
          controller: logic.searchCtrl,
          focusNode: logic.focusNode,
          autofocus: true,
          decoration: InputDecoration(
            hintText: '搜索',
            hintStyle: Styles.ts_8E9AB0_16sp,
            border: InputBorder.none,
            contentPadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
            suffixIcon: ValueListenableBuilder<TextEditingValue>(
              valueListenable: logic.searchCtrl,
              builder: (context, value, child) {
                return value.text.trim().isNotEmpty
                    ? IconButton(
                        icon: Icon(Icons.clear, size: 20.w, color: Styles.c_8E9AB0),
                        onPressed: logic.clearSearch,
                      )
                    : SizedBox();
              },
            ),
          ),
          style: Styles.ts_0C1C33_14sp,
          textInputAction: TextInputAction.search,
          onSubmitted: (_) => logic.performSearch(),
        ),
      ),
      actions: [
        TextButton(
          onPressed: logic.performSearch,
          child: Text('搜索', style: Styles.ts_0089FF_16sp),
        ),
      ],
    );
  }


  // 构建搜索类型筛选器
  Widget _buildSearchTypeFilter() {
    return Container(
      height: 44.h,
      color: Styles.c_FFFFFF,
      child: Obx(() => Row(
        children: List.generate(logic.tabs.length, (index) {
          final isSelected = logic.index.value == index;
          return Expanded(
            child: GestureDetector(
              onTap: () => logic.switchTab(index),
              child: Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: isSelected ? Styles.c_0089FF : Colors.transparent,
                      width: 2.h,
                    ),
                  ),
                ),
                child: Text(
                  logic.tabs[index],
                  style: isSelected ? Styles.ts_0089FF_16sp : Styles.ts_8E9AB0_16sp,
                ),
              ),
            ),
          );
        }),
      )),
    );
  }

 Widget _buildSearchContent() {
  final currentList = _getCurrentList();
  
  // 修复响应式变量访问
  if (!logic.hasSearched.value) {
    return _buildEmptyState();
  }
  
  if (logic.isSearching.value) {
    return _buildLoadingState();
  }
  
  if (currentList.isEmpty) {
    return _buildNoResultState();
  }
  
  return _buildSearchResults();
}

  // 获取当前选中tab的数据列表
  List<dynamic> _getCurrentList() {
    switch (logic.index.value) {
      case 0: // 全部
        return [
          ...logic.contactsList,
          ...logic.groupList,
          ...logic.textSearchResultItems,
          ...logic.fileMessageList,
        ];
      case 1: // 联系人
        return logic.contactsList;
      case 2: // 群组
        return logic.groupList;
      case 3: // 聊天记录
        return logic.textSearchResultItems;
      case 4: // 文件
        return logic.fileMessageList;
      default:
        return [];
    }
  }

  // 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.search,
            size: 64.w,
            color: Styles.c_8E9AB0,
          ),
          16.verticalSpace,
          Text(
            '输入关键词开始搜索',
            style: Styles.ts_8E9AB0_16sp,
          ),
        ],
      ),
    );
  }

  // 构建加载状态
  Widget _buildLoadingState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(color: Styles.c_0089FF),
          16.verticalSpace,
          Text('搜索中...', style: Styles.ts_8E9AB0_16sp),
        ],
      ),
    );
  }

  // 构建无结果状态
  Widget _buildNoResultState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.search_off,
            size: 64.w,
            color: Styles.c_8E9AB0,
          ),
          16.verticalSpace,
          Text(
            '未找到相关内容',
            style: Styles.ts_8E9AB0_16sp,
          ),
          8.verticalSpace,
          Text(
            '尝试使用其他关键词',
            style: Styles.ts_8E9AB0_14sp,
          ),
        ],
      ),
    );
  }

   // 构建搜索结果列表
  Widget _buildSearchResults() {
    // 如果不是"全部"标签，使用原有逻辑
    if (logic.index.value != 0) {
      final currentList = _getCurrentList();
      return ListView.builder(
        padding: EdgeInsets.symmetric(vertical: 8.h),
        itemCount: currentList.length,
        itemBuilder: (context, index) {
          final item = currentList[index];
          
          if (item is FriendInfo) {
            return _buildContactItem(item);
          } else if (item is GroupInfo) {
            return _buildGroupItem(item);
          } else if (item is SearchResultItems) {
            return _buildChatHistorySection(item);
          } else if (item is Message) {
            return _buildFileMessageItem(item);
          }
          
          return SizedBox();
        },
      );
    }
    // "全部"标签页：按分类显示
    return _buildCategorizedResults();
  }

   // 构建分类搜索结果
  Widget _buildCategorizedResults() {
    final List<Widget> sections = [];
    
    // 联系人分类
    if (logic.contactsList.isNotEmpty) {
      sections.add(_buildSectionHeader('联系人'));
      sections.addAll(logic.contactsList.map((contact) => _buildContactItem(contact)));
    }
    
    // 群聊分类
    if (logic.groupList.isNotEmpty) {
      sections.add(_buildSectionHeader('群组'));
      sections.addAll(logic.groupList.map((group) => _buildGroupItem(group)));
    }
    
    // 聊天记录分类
    if (logic.textSearchResultItems.isNotEmpty) {
      sections.add(_buildSectionHeader('聊天记录'));
      sections.addAll(logic.textSearchResultItems.map((item) => _buildChatHistorySection(item)));
    }
    
    // 文件分类
    if (logic.fileMessageList.isNotEmpty) {
      sections.add(_buildSectionHeader('文件'));
      sections.addAll(logic.fileMessageList.map((message) => _buildFileMessageItem(message)));
    }
    
    return ListView(
      padding: EdgeInsets.symmetric(vertical: 8.h),
      children: sections,
    );
  }

  // 构建分类标题
  Widget _buildSectionHeader(String title) {
    return Container(
      padding: EdgeInsets.fromLTRB(12.w, 16.h, 12.w, 8.h),
      child: Text(
        title,
        style: Styles.ts_8E9AB0_14sp.copyWith(
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }


  // 构建联系人项
  Widget _buildContactItem(FriendInfo contact) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
      decoration: BoxDecoration(
        color: Styles.c_FFFFFF,
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: ListTile(
        leading: AvatarView(
          url: contact.faceURL,
          text: contact.nickname,
          width: 42.w,
        ),
        title: Text(
          contact.nickname ?? '',
          style: Styles.ts_0C1C33_14sp,
        ),
        // subtitle: Text(
        //   '联系人',
        //   style: Styles.ts_8E9AB0_10sp,
        // ),
        onTap: () => logic.openUserProfile(contact),
      ),
    );
  }

  // 构建群组项
  Widget _buildGroupItem(GroupInfo group) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
      decoration: BoxDecoration(
        color: Styles.c_FFFFFF,
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: ListTile(
        leading: AvatarView(
          url: group.faceURL,
          text: group.groupName,
          width: 42.w,
          isGroup: true,
        ),
        title: Text(
          group.groupName ?? '',
          style: Styles.ts_0C1C33_14sp,
        ),
        // subtitle: Text(
        //   '群聊',
        //   style: Styles.ts_8E9AB0_10sp,
        // ),
        onTap: () => logic.openGroupChat(group),
      ),
    );
  }

    Widget _buildChatHistorySection(SearchResultItems searchResult) {
    if (searchResult.messageList?.isEmpty == true) return SizedBox();
    
    final firstMessage = searchResult.messageList!.first;
    
    return FutureBuilder<Map<String, String>>(
      future: _getChatDisplayInfo(firstMessage),
      builder: (context, snapshot) {
        final displayInfo = snapshot.data ?? {
          'showName': firstMessage.sessionType == ConversationType.single 
              ? (firstMessage.sendID == OpenIM.iMManager.userID ? '对方' : firstMessage.senderNickname ?? '对方')
              : firstMessage.groupID ?? '群聊',
          'faceURL': firstMessage.sessionType == ConversationType.single 
              ? (firstMessage.sendID == OpenIM.iMManager.userID ? '' : firstMessage.senderFaceUrl ?? '')
              : '',
        };
        
        final showName = displayInfo['showName']!;
        final faceURL = displayInfo['faceURL']!;
        final isGroup = firstMessage.sessionType == ConversationType.superGroup || 
                       firstMessage.sessionType == ConversationType.group;
        
        return Container(
          margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
          decoration: BoxDecoration(
            color: Styles.c_FFFFFF,
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 会话标题
              Padding(
                padding: EdgeInsets.all(12.w),
                child: Row(
                  children: [
                    AvatarView(
                      url: faceURL,
                      text: showName,
                      width: 36.w,
                      isGroup: isGroup,
                    ),
                    12.horizontalSpace,
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            showName,
                            style: Styles.ts_0C1C33_14sp.copyWith(fontWeight: FontWeight.w500),
                          ),
                          2.verticalSpace,
                          Text(
                            isGroup ? '群聊' : '联系人',
                            style: Styles.ts_8E9AB0_10sp,
                          ),
                        ],
                      ),
                    ),
                    Text(
                      '${searchResult.messageList?.length ?? 0}条相关记录',
                      style: Styles.ts_8E9AB0_12sp,
                    ),
                  ],
                ),
              ),
              // 消息列表
              ...searchResult.messageList!.take(3).map((message) => _buildMessageItem(message)),
              if (searchResult.messageList!.length > 3)
                Padding(
                  padding: EdgeInsets.all(12.w),
                  child: GestureDetector(
                    onTap: () => logic.viewMoreMessages(searchResult),
                    child: Text(
                      '查看更多消息',
                      style: Styles.ts_0089FF_14sp,
                    ),
                  ),
                ),
            ],
          ),
        );
      },
    );
  }

    // 修改获取聊天显示信息的方法
  Future<Map<String, String>> _getChatDisplayInfo(Message firstMessage) async {
    if (firstMessage.sessionType == ConversationType.single) {
      if (firstMessage.sendID == OpenIM.iMManager.userID) {
        // 获取对方真实昵称
        final otherUserID = firstMessage.recvID!;
        final nickname = await logic.getRealUserNickname(otherUserID);
        return {
          'showName': nickname,
          'faceURL': '', // 需要额外获取对方头像
        };
      } else {
        final nickname = await logic.getRealUserNickname(firstMessage.sendID!);
        return {
          'showName': nickname,
          'faceURL': firstMessage.senderFaceUrl ?? '',
        };
      }
    } else {
      // 获取群聊真实信息
      final groupInfo = await logic.getRealGroupInfo(firstMessage.groupID!);
      return {
        'showName': groupInfo['groupName']!,
        'faceURL': groupInfo['faceURL']!,
      };
    }
  }
  // 构建消息项
  Widget _buildMessageItem(Message message) {
    final content = logic.getMessageDisplayContent(message);
    final time = logic.formatMessageTime(message.sendTime!);
    
    return GestureDetector(
      onTap: () => logic.jumpToMessage(message),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
        decoration: BoxDecoration(
          border: Border(
            top: BorderSide(color: Styles.c_E8EAEF, width: 0.5.h),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(
                  message.senderNickname ?? '',
                  style: Styles.ts_0C1C33_14sp.copyWith(fontWeight: FontWeight.w500),
                ),
                Spacer(),
                Text(
                  time,
                  style: Styles.ts_8E9AB0_12sp,
                ),
              ],
            ),
            4.verticalSpace,
            if (message.contentType == MessageType.text)
              RichText(
                text: TextSpan(
                  children: logic.getHighlightedText(content, logic.searchKey),
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              )
            else
              Text(
                content,
                style: Styles.ts_8E9AB0_14sp,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
          ],
        ),
      ),
    );
  }

  // 构建文件消息项
  Widget _buildFileMessageItem(Message message) {
    final content = logic.getMessageDisplayContent(message);
    final time = logic.formatMessageTime(message.sendTime!);
    
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
      decoration: BoxDecoration(
        color: Styles.c_FFFFFF,
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: ListTile(
        leading: Icon(
          Icons.insert_drive_file,
          color: Styles.c_0089FF,
          size: 32.w,
        ),
        title: Text(
          content,
          style: Styles.ts_0C1C33_10sp,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        subtitle: Text(
          '来自 ${message.senderNickname} · $time',
          style: Styles.ts_8E9AB0_14sp,
        ),
        onTap: () => logic.jumpToMessage(message),
      ),
    );
  }
}